import datetime
import json
import os

import pymysql
import requests
import time

from Base import Log, GetYamlFile
from Base.GetYamlFile import getYamlPath
from Base.HttpBase import HttpBase
from Base.ReadExcel import Read_Excel

log = Log.Log()
# base_url = 'http://192.168.17.236:30810'  # 独立租户2环境
# base_url = 'http://192.168.17.236:30510'  # 独立租户1环境
base_url = 'http://111.20.218.54:30510'  # 凤县线上环境
login_api = base_url + '/upms-provider/tenant/user/login/mobile'
login_data = {
    'mobile': '18368093710',
    'password': 'Aa123456'
}
headers = {
    'Content-Type': 'application/json'
}
token = HttpBase(login_api, login_data, 'post', headers).getHttpHeaders().get('access_token')
Refresh_token = HttpBase(login_api, login_data, 'post', headers).getHttpHeaders().get('Refresh_token')
log.info(token)
# 基础数据
base_data = {
    'orderId': 141098578501701,
    'tenantId': 1,
    'customerId': 30817,
    'customerName': '对账企业',
    'orderGoodsId': 141098578690117,
    'licensePlate': '浙C00001',
    'driverPhone': '18368033333',
}
num = 10000  # 新增条数
sql_config = getYamlPath("SqlConfigBasic")
basic_conn = pymysql.connect(**sql_config)
cur = basic_conn.cursor()
# 根据手机号获取司机名称及id赋值
select_sql = '''
            SELECT driver_name,id  FROM bs_driver WHERE phone = %s
        '''
test = cur.execute(select_sql, base_data.get('driverPhone'))
test = cur.fetchall()
base_data['driverName'] = test[0][0]
base_data['driverId'] = test[0][1]
# 基础请求头
base_headers = {
    'type': 'tenant',
    'tenant_id': str(base_data.get('tenantId')),
    'access_token': token,
    'Refresh_token': Refresh_token,
    # 'Version': 'middleground-2.0.5.6-SNAPSHOT'
}


def add_account():
    account_save_url = base_url + '/tenant-lms-account-provide/capitalReceipt/save'
    account_check_url = base_url + '/tenant-lms-account-provide/capitalReceipt/check'
    data = {
        'tenantId': base_data.get('tenantId'),
        'tenantName': '博峰租户',
        'billTime': '2023-05-12 10:33:20',
        'payTime': '2023-05-12 10:33:20',
        'customerId': base_data.get('customerId'),
        'customerName': base_data.get('customerName'),
        'receiptRecordQos': [{
            'customerId': base_data.get('customerId'),
            'businessType': '299',
            'money': '1',
            'payType': '1',
            'collectAccount': '1',
            'customerName': '收款单客户测试1',
            'businessTypeName': '水泥',
            'num': 1,
            'key': 0
        }]
    }
    add_headers = base_headers
    add_headers['Content-Type'] = 'application/json'
    print(add_headers)
    i = 0
    while i < 17:
        result = HttpBase(account_save_url, data, 'post', add_headers).getHttpBody()
        i += 1
        log.info(str(result, 'utf-8'))
    sql_config = getYamlPath("SqlConfig")
    conn = pymysql.connect(**sql_config)
    cur = conn.cursor()
    select_sql = '''
            select id from capital_receipt where customer_id = %s
        '''
    test = cur.execute(select_sql, base_data.get('customerId'))
    test = cur.fetchall()
    check_headers = base_headers
    for e in test:
        data = e[0]
        result = HttpBase(account_check_url, data, 'put', check_headers).getHttpBody()
        log.info(result)


def add_invoice():
    invoice_add_url = base_url + '/tenant-lms-sales-provide/lms/business/sales/order/dispatch'
    invoice_data = [{
        'orderGoodsId': base_data.get('orderGoodsId'),
        'uniqueKey': 0,
        'num': '1',
        'isSample': False,
        'billingFactoryCode': '1',
        'billingFactoryName': '铜川声威建材有限责任公司安塞分公司',
        'billDate': datetime.datetime.now().isoformat(timespec='milliseconds') + 'Z',
        'licensePlate': base_data.get('licensePlate'),
        'vehicleCargoTotalWeight': None,
        'vehicleTare': None,
        'maxLoadLimit': 60,
        'isMaxLoadLimit': True,
        'driverPhone': base_data.get('driverPhone'),
        'driverName': base_data.get('driverName'),
        'driverId': base_data.get('driverId'),
        'amount': '1'
    }]
    invoice_headers = base_headers
    invoice_headers['Content-Type'] = 'application/json'

    i = 0
    while i < num:
        start_time = time.time()
        flag = False
        is_result_true(flag, invoice_add_url, invoice_data, invoice_headers)
        # result = HttpBase(invoice_add_url, invoice_data, 'post', invoice_headers).getHttpBody()
        i += 1
        log.info("生成第%s条销售发货订单" % i)
        weight()
        end_time = time.time()
        log.info('ERP完成一条销售发货单创建到计量完成时间：%s' % (end_time - start_time))
        log.info('剩余条数：%s 及所需要时间：%s' % ((num - i), ((end_time - start_time) * (num - i))))


def weight():
    '''
    仅支持默认过磅流程 接单->入厂->一次过磅->装卸货->二次过磅->出厂流程
    :return:
    '''
    meter_sql_config = getYamlPath("SqlConfigMeter")
    conn = pymysql.connect(**meter_sql_config)
    cur = conn.cursor()
    # 计量表中获取status=0（激活状态）,order_id动态的计量单
    select_sql = '''
            SELECT id, logistics_num  FROM calculate_logistics WHERE `status` =0 AND order_id =%s
        '''
    test = cur.execute(select_sql, base_data.get('orderId'))
    # 查询结果，并返回元组
    test = cur.fetchall()
    # 循环获取每个元组数据，且分别获取logistics_num、logistics_id数据
    for e in test:
        flag = False
        logistics_num = e[1]
        logistics_id = int(e[0])
        #
        take_order_url = base_url + '/tenant-lms-meter-provide/lms/meter/calculate/logistics/takeOrder?status=1&logisticsNum=' + logistics_num
        # print(logistics_num)
        # 判断接单结果是否正确，不正确则重新请求，直到正常为止
        while flag is False:
            take_result_result = requests.put(take_order_url, headers=base_headers)
            # 判断接单结果是否正常，不正常则重新请求，直到正常为止
            while take_result_result.status_code != 200:
                log.error("服务器返回异常，休眠10s后重新发送请求")
                log.error("失败记录：" + str(take_result_result.content, 'utf-8'))
                time.sleep(10)
                take_result_result = requests.put(take_order_url, headers=base_headers)
            log.info(str(take_result_result.content, 'utf-8'))
            take_result_result = json.loads(str(take_result_result.content, 'utf-8'))
            # 判断司机是否已接单或者接单成功
            if (take_result_result['success'] == True or take_result_result['code'] == '7020'):
                flag = True
            # print(flag)
        flag = False
        pass_door_url = base_url + '/tenant-lms-meter-provide/lms/meter/calculate/door/passDoor'
        pass_door_data = {
            "id": logistics_id,
            "time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        }
        pass_door_header = base_headers
        pass_door_header['Content-Type'] = 'application/json'
        # 判断入厂结果是否正确，不正确则重新请求，直到正常为止
        is_result_true(flag, pass_door_url, pass_door_data, pass_door_header)
        flag = False
        determine_start_time = time.time()
        weighting_url = base_url + '/tenant-lms-meter-provide/lms/meter/calculate/logisticsWeighing/weighting'
        weighting_data = {
            "id": logistics_id, "time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "weighing": "2"
        }
        # 判断结果是否正确，不正常则重新请求，直到正常为止
        is_result_true(flag, weighting_url, weighting_data, pass_door_header)
        flag = False
        load_url = base_url + '/tenant-lms-meter-provide/lms/meter/calculate/logistics/load'
        load_data = {
            "id": logistics_id, "loadFlag": "load"
        }
        # 判断结果是否正确，不正常则重新请求，直到正常为止
        is_result_true(flag, load_url, load_data, pass_door_header)
        flag = False
        load_data['loadFlag'] = 'unload'
        # 判断结果是否正确，不正常则重新请求，直到正常为止
        is_result_true(flag, load_url, load_data, pass_door_header)
        flag = False
        weighting_data['weighing'] = '3'
        # 判断结果是否正确，不正常则重新请求，直到正常为止
        is_result_true(flag, weighting_url, weighting_data, pass_door_header)
        flag = False
        # 判断结果是否正确，不正常则重新请求，直到正常为止
        while flag is False:
            '''
            /tenant-lms-meter-provide/lms/meter/calculate/door/passDoor 接口存在5s限制调用
            判断接口调用是否在5s内调用，有则休眠等待
            '''
            while time.time() - determine_start_time < 5:
                log.info("时间未达到5秒：现在为%s秒，休眠1秒" % (time.time() - determine_start_time))
                time.sleep(1)
            pass_door_result = requests.post(pass_door_url, json=pass_door_data, headers=pass_door_header)
            while pass_door_result.status_code != 200:
                log.error("服务器返回异常，休眠10s后重新发送请求")
                log.error("失败记录：" + str(pass_door_result.content, 'utf-8'))
                time.sleep(10)
                pass_door_result = requests.post(pass_door_url, json=pass_door_data, headers=pass_door_header)
            log.info(str(pass_door_result.content, 'utf-8'))
            pass_door_result = json.loads(str(pass_door_result.content, 'utf-8'))
            flag = dict(pass_door_result)['success']
        log.info('计量执行成功')


def is_result_true(flag, url, data, header_list):
    while flag is False:
        result = requests.post(url, json=data, headers=header_list)
        while result.status_code != 200:
            log.error("服务器返回异常，休眠10s后重新发送请求")
            log.error("失败记录：" + str(result.content, 'utf-8'))
            time.sleep(10)
            result = requests.post(url, json=data, headers=header_list)
        log.info(str(result.content, 'utf-8'))
        log.info('运行时间：%s秒' % str(result.elapsed.seconds))
        result = json.loads(str(result.content, 'utf-8'))
        flag = dict(result)['success']


def car_add():
    """
车辆添加
    """
    list1 = []
    car_save_url = base_url + '/tenant-lms-basic-provide/lms/basic/car/save'
    add_headers = base_headers
    add_headers['Content-Type'] = 'application/json'
    data = {

    }
    yml_list = GetYamlFile.getYamlFile()
    carPath = yml_list["carPath"]
    PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))
    REPORT_XLSX_DIR = os.path.join(PROJECT_ROOT, carPath)
    readBook = Read_Excel(REPORT_XLSX_DIR)
    num = readBook.get_RowNums("sheet")
    for i in range(1, num):
        name = readBook.read_Excel("sheet", i, 0)
        data = {
            "tenantName": "凤县声威建材有限公司",
            "tenantCode": "",
            "licensePlate": name,
            "axleType": "",
            "axleVehicleType": "",
            "countryStandard": "",
            "deadweight": "",
            "emptyTare": "",
            "annualSurveyMonthDate": "",
            "haveEtc": "",
            "haveSpeedWing": "",
            "isBlacklist": False,
            "carCategory": "",
            "energyType": "",
            "tenantId": "2561",
            "tiepieceSite": "",
            "tiepieceCount": 1
        }
        result = requests.post(car_save_url, json=data, headers=add_headers)
        print(str(result.content, 'utf-8'))
        print(type(result.content))
        if json.loads(result.content).get("message") == "车牌号已存在，请输入新的车牌！":
            list1.append(name)
    print(list1)


def price_add():
    """
价格单导入
    """
    add_headers = base_headers
    yml_list = GetYamlFile.getYamlFile()
    pricePath = yml_list["pricePath"]
    PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))
    REPORT_XLSX_DIR = os.path.join(PROJECT_ROOT, pricePath)
    readBook = Read_Excel(REPORT_XLSX_DIR)
    num = readBook.get_RowNums("sheet")
    print(num)
    list1 = []

    for i in range(1, num):
        pName = readBook.read_Excel("sheet", i, 7)
        product_code = readBook.read_Excel("sheet", i, 6)
        customer_code = readBook.read_Excel("sheet", i, 2)
        jiesuan = readBook.read_Excel("sheet", i, 12)
        jiesuancode = readBook.read_Excel("sheet", i, 11)
        price = readBook.read_Excel("sheet", i, 14)
        page_union_url = base_url + '/tenant-lms-basic-provide/lms/basic/customer/pageUnion'
        project_customer_url = base_url + '/tenant-lms-basic-provide/projectCustomer/list'
        product_url = base_url + '/tenant-lms-basic-provide/lms/basic/product/list'
        price_add_url = base_url + '/tenant-lms-price-provide/priceList/save'
        customer_data = {
            'status': 0,
            'auditStatus': 1,
            'current': 1,
            'size': 10,
            'nameOrCode': customer_code
        }
        print(customer_code)
        result = requests.get(page_union_url, customer_data, headers=add_headers)
        customer_name = json.loads(result.content).get("data").get('records')[0].get('name')
        customer_id = json.loads(result.content).get("data").get('records')[0].get('id')
        customer_code = json.loads(result.content).get("data").get('records')[0].get('code')
        customer_category_name = json.loads(result.content).get("data").get('records')[0].get('customerCategoryName')
        customer_category_id = json.loads(result.content).get("data").get('records')[0].get('customerCategoryId')
        customer_short_name = json.loads(result.content).get("data").get('records')[0].get('shortName')
        project_customer_data = {
            'customerId': customer_id,
            'status': 1
        }
        project_customer_result = requests.get(project_customer_url, project_customer_data, headers=add_headers)
        print(str(project_customer_result.content, 'utf-8'))
        product_data = {
            'auditStatus': 1,
            'productCode': product_code,
            'current': 1,
            'size': 5
        }
        product_result = requests.get(product_url, product_data, headers=add_headers)
        print(str(product_result.content, 'utf-8'))
        price_list_name = json.loads(project_customer_result.content).get("data")[0].get(
            'projectName') + '-' + pName + '-' + jiesuan + '价目表'
        price_add_data = {
            "isAdjust": 1,
            "tenantId": 2561,
            "endExpireTime": "",
            "priceListName": price_list_name,
            "customerId": customer_id,
            "customerCode": customer_code,
            "customerName": customer_name,
            "customerCategoryName": customer_category_name,
            "customerCategoryId": customer_category_id,
            "customerSalesType": None,
            "customerSalesTypeName": None,
            "customerShortName": customer_short_name,
            "siteId": "",
            "startExpireTime": "2023-08-18 17:03:34",
            "checkStatus": 1,
            "priceListGoodsQos": [{
                "categoryId": json.loads(product_result.content).get("data").get('records')[0].get('categoryId'),
                "productId": json.loads(product_result.content).get("data").get('records')[0].get('id'),
                "productName": json.loads(product_result.content).get("data").get('records')[0].get('productName'),
                "productCode": json.loads(product_result.content).get("data").get('records')[0].get('productCode'),
                "categoryName": json.loads(product_result.content).get("data").get('records')[0].get('category'),
                "unitName": json.loads(product_result.content).get("data").get('records')[0].get('unit'),
                "unitId": json.loads(product_result.content).get("data").get('records')[0].get('unitId'),
                "price": price,
                "productPrice": price,
                "transportPrice": 0,
                "taxRate": json.loads(product_result.content).get("data").get('records')[0].get('taxRate'),
                "currency": "人民币",
                "priceModel": 2,
                "flowControl": 2,
                "payType": jiesuancode,
                "siteId": "",
                "projectId": json.loads(project_customer_result.content).get("data")[0].get('projectId'),
                "num": 1,
                "key": 0,
                "projectName": json.loads(project_customer_result.content).get("data")[0].get('projectName'),
                "subAccountId": json.loads(project_customer_result.content).get("data")[0].get('subAccountId'),
                "payTypeName": jiesuan
            }],
            "businessRouteUrl": "/lms-web/#/dealPriceDetailH5?id=",
            "priceListType": 2,
            "tenantName": "凤县声威建材有限公司"
        }
        print(product_code, customer_code, i)
        post_header = base_headers
        post_header['Content-Type'] = 'application/json'
        result = requests.post(price_add_url, json=price_add_data, headers=post_header)
        print(str(result.content, 'utf-8'))
        # print('拿到code:'+str(json.loads(result.content).get('code')))
        if json.loads(result.content).get('code') != 0:
            print('----执行失败，记录code-----')
            list1.append(customer_code)
    print(list1)


def shoukuandan():
    """
收款单导入
    """
    add_headers = base_headers
    yml_list = GetYamlFile.getYamlFile()
    pricePath = yml_list["yyPath"]
    PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))
    REPORT_XLSX_DIR = os.path.join(PROJECT_ROOT, pricePath)
    readBook = Read_Excel(REPORT_XLSX_DIR)
    num = readBook.get_RowNums("sheet")
    print(num)
    list1 = []
    for i in range(3, num):
        customer_code = readBook.read_Excel("sheet", i, 0)
        money = readBook.read_Excel("sheet", i, 3)
        project_customer_url = base_url + '/tenant-lms-basic-provide/projectCustomer/list'
        page_union_url = base_url + '/tenant-lms-basic-provide/lms/basic/customer/pageUnion'
        account_list = base_url + '/tenant-lms-account-provide/capitalAccount/page'

        customer_data = {
            'status': 0,
            'auditStatus': 1,
            'current': 1,
            'size': 10,
            'nameOrCode': customer_code
        }
        result = requests.get(page_union_url, customer_data, headers=add_headers)
        print('111' + str(result.content, 'utf-8'))
        print(customer_code)
        customer_name = json.loads(result.content).get("data").get('records')[0].get('name')
        customer_id = json.loads(result.content).get("data").get('records')[0].get('id')

        print('111222' + customer_id)
        list_data = {
            'current': 1,
            'size': 50,
            'type': 1,
            'tenantId': 2561,
            'customerId': customer_id
        }
        list_result = requests.post(account_list, params=list_data, headers=add_headers)
        account_list_id = json.loads(list_result.content).get("data").get('records')[0].get('id')
        # print(list_result)
        print(account_list_id)
        print(customer_code)
        print(money)
        date = {
            "tenantId": 2561,
            "tenantName": "凤县声威建材有限公司",
            "payTime": "2023-08-22 00:50:49",
            "customerId": customer_id,
            "customerName": customer_name,
            "checkStatus": 3,
            "receiptRecordQos": [{
                "customerId": customer_code,
                "summaryContentCode": "1",
                "businessTypeCode": "1",
                "payType": "7",
                "paymentMethodCode": "0",
                "accountId": account_list_id,
                "accountName": "通用账户",
                "money": money,
                "customerName": customer_name,
                "summaryContent": "水泥款",
                "businessTypeName": "水泥款",
                "businessType": "526",
                "paymentMethodName": "现金",
                "num": 1,
                "key": 0
            }],
            "businessRouteUrl": "/lms-web/#/receiptVoucherDetailH5?id="
        }
        account_save = base_url + '/tenant-lms-account-provide/capitalReceipt/save'
        account_save_result = requests.post(account_save, json=date, headers=add_headers)
        print(str(account_save_result.content, 'utf-8'))


if __name__ == '__main__':
    # price_add()
    # weight()
    # data = "{'code':0,'message':'请求成功!','data':null,'ext':null,'success':true}"
    # data1 = eval(data)
    # print(data1['success'])

    t1 = {
        "id": 1,
        "id2": 2,
        "id3": 3,
    }
    t2 = {
        "id": 2
    }

    t2 = {k: v for k, v in t1.items() if k in t2}

    print(t2)
